package com.talkyoung.ptbpro.component;

import com.talkyoung.ptbpojo.entity.User;
import com.talkyoung.ptbpojo.entity.UserPermission;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import sun.java2d.pipe.SpanShapeRenderer;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class UserDetailsImpl implements UserDetails {
    private User user;
    private List<UserPermission> authorityList;

//    private Collection<? extends GrantedAuthority> authorities;

    public UserDetailsImpl(User user,List<UserPermission> authorityList) {
        this.user = user;
        this.authorityList = authorityList;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

//        List<SimpleGrantedAuthority> simpleGrantedAuthorities = null;
//        for(UserPermission userPermission:authorityList){
//            simpleGrantedAuthorities.add(new SimpleGrantedAuthority(userPermission.getValue()));
//        }
//        return simpleGrantedAuthorities;

        //返回当前用户的权限
        //map是将每一个对象转变成另一个对象
        return authorityList.stream()
                .filter(permission -> permission.getValue()!=null)
                .map(permission ->new SimpleGrantedAuthority(permission.getValue()))
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    // 账号是否未过期，默认是false
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    // 账号是否未锁定，默认是false
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    // 账号凭证是否未过期，默认是false
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
